package com.xinxin.datastructure.map.impl;

import com.xinxin.datastructure.map.Map;

/**
 * @author ：史鑫鑫
 * @date ：Created in 2019/5/7 23:48
 */
public class LinedkListMap<K, V> implements Map<K, V> {
    // 节点内部类
    private class Node {
        K key;
        V value;
        Node next;

        Node(K key, V value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public Node(K key) {
            this(key, null, null);
        }

        Node() {
            this(null, null, null);
        }

        @Override
        public String toString() {
            return key.toString() + ":" + value.toString();
        }
    }

    private Node dummyHhead;
    private int size;

    /// 构造函数，创建虚拟头结点
    public LinedkListMap() {
        dummyHhead = new Node();
        size = 0;
    }

    private Node getNode(K key) {
        Node cur = dummyHhead.next;
        while (cur != null) {
            if (key.equals(cur.key)) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if (node == null) {
            dummyHhead.next = new Node(key, value, dummyHhead.next);
            size++;
        } else {
            node.value = value;
        }
    }

    @Override
    public V remove(K key) {
        Node prev = dummyHhead;
        while (prev.next != null) {
            if (key.equals(prev.next.key)) {
                break;
            }
            prev = prev.next;
        }
        if (prev.next != null) {
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size--;
            return delNode.value;
        }
        return null;
    }

    @Override
    public boolean contains(K key) {
        return getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.value;
    }

    @Override
    public void set(K key, V newValue) {
        Node node = getNode(key);
        if (node == null) {
            throw new IllegalArgumentException(key + " doesn't exist!");
        }
        node.value = newValue;

    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        Node cur = dummyHhead.next;
        while (cur != null) {
            res.append(cur.key).append(":").append(cur.value).append("\n");
            cur = cur.next;
        }
        return res.toString();
    }
}
